<template>
  <!-- // 分配角色 -->
  <div>
    <el-tree
      ref="refTree"
      :data="permissionData"
      default-expand-all
      :props="{label: 'name'}"
      show-checkbox
      node-key="id"
      :check-strictly="true"
    />

    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permissions'
import { tranlistToTreeList } from '@/utils/index'
import { getOneRoles, assignPerm } from '@/api/settings'
export default {
  props: {
    curId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissionData: [] // 存储权限数据

    }
  },
  created() {
    this.loadPermissionList()
    this.loadPermission()
  },
  methods: {
    // 获取所有的权限点
    async loadPermissionList() {
      try {
        // 发送请求, 获取权限列表
        const { data } = await getPermissionList()
        console.log('权限列表的数据是', data)
        this.permissionData = tranlistToTreeList(data)
      } catch (err) {
        console.log(err)
      }
    },
    // 根据id获取当前角色的权限
    async loadPermission() {
      try {
        const res = await getOneRoles(this.curId)
        console.log('获取当前角色的已有的权限点数据', res.data.permIds)
        this.$refs.refTree.setCheckedKeys(res.data.permIds)
      } catch (err) {
        console.log(err)
      }
    },
    // 确定
    async hSubmit() {
      // 所有选中的节点的id组成的数组
      const permIds = this.$refs.refTree.getCheckedKeys()
      try {
        const res = await assignPerm({ id: this.curId, permIds })
        console.log(res)
        this.$emit('close')
      } catch (err) {
        console.log(err)
      }
    },
    // 取消
    closeDialog() {
      this.$emit('close')
    }
  }
}
</script>

